import re
import os
from cli import Cli
import sys
sys.path.append("..")

match_id_and_name = r'(^\d+)(.+)'
match_id = r'(^\d+)'


def find_latest_modify(persons):
    mapping = dict()
    for rawid, info in persons:
        matchs = re.findall(match_id, rawid)
        if matchs == None or len(matchs) == 0:
            print("{0} 异常数据".format(rawid))
            continue
        id = matchs[0]
        prev = mapping.get(id)
        if(prev != None):
            _, prev = prev
            if prev['modify'] < info['modify']:
                mapping[id] = (rawid, info)
        else:
            mapping[id] = (rawid, info)

    result = []
    for key in mapping:
        result.append(mapping.get(key))
    return result


def get_list_filename(files):
    return list(map(lambda item: item[0], files))


def find_not_submit_homework(filename: str, persons):
    classes_person = dict()
    classes_list = []
    persons_list = list(
        map(lambda item: re.findall(match_id, item)[0], persons))
    try:
        with open(os.path.join(filename)) as fp:
            for line in fp.readlines():
                id, name = line.strip().split(" ")
                classes_person[id] = name
                classes_list.append(id)
    except FileNotFoundError:
        return False

    not_submit = list(set(classes_list) - set(persons_list))

    return list(map(lambda item: (item, classes_person[item]), not_submit))


def diff_dir(ctx: Cli, filename: str, itemname: str):
    current_dir = ctx.ftp.pwd
    for name, _ in sorted(ctx.ftp.get_list_of_type(t = 'dir')):
        print(name)
        ctx.ftp.change_dir(os.path.join(current_dir, name))
        diff_files(ctx, filename, itemname)
        print("\n\n")
    ctx.ftp.change_dir(current_dir)

def diff_files(ctx: Cli, filename: str, name: str):
    result = ctx.ftp.get_list_of_type(t = "file")
    result = get_list_filename(find_latest_modify(result))

    print("共 %d 条数据" % len(result))

    result = find_not_submit_homework(filename, result)

    result = list(map(lambda item: (item[0], item[1]), result))

    result.sort(key=lambda item: item[0])



    print("未匹配 %d 数据" % len(result))


    if name == None:
        if len(result) != 0:
            for item in result:
                print("{0}:{1}".format(item[0], item[1]))
        else:
            print("全部提交")
    else:
        result = list(filter(lambda item: re.search(name, "{0} {1}".format(item[0], item[1])) != None, result))
        if len(result) > 0:
            print("未找到")
        else:
            print("已提交")



# export
def diff(ctx: Cli, args: (dict, list, list)):
    arg, _, _ = args
    filename = arg.get("filename")
    deep = arg.get("deep")
    name = arg.get("name")

    if not filename:
        print("请输入文件路径")
        return
    if not os.path.isabs(filename):
        filename = os.path.join(os.getcwd(), filename)

    if not os.path.realpath(filename):
        print("该文件不存在")
        return

    if not os.path.isfile(filename):
        print("该路径不是文件，请输入正确的路径")
        return

    # if not abs

    if deep:
        diff_dir(ctx, filename, name)
    else:
        diff_files(ctx, filename, name)
